
const ArticleModel = require('./../models/article')
const ArticleCode = require('./../../codes/Article')
const ServerCode = require('./../../codes/server')
const { handleSuccess, handleFail } = require('./../../utils/handle')


class Article {
  static async list(ctx) {
    const postData = ctx.request.body

    await ArticleModel.getArticles().then(async res => {
      if (res.length) {
        handleSuccess(ctx, { status: 200, message: ArticleCode.SUCCESS_GET_ARTICLES, code: 10001, data: res })
      } else {
        handleSuccess(ctx, { message: ArticleCode.ERROR_ARTICLE_FOUND, code: 404, data: null })
      }
    }).catch(err => {
      handleFail({ message: ServerCode.ERROR_SERVER, code: 500, data: null })
    })
  }
  static async create(ctx) {
    const postData = ctx.request.body

    await ArticleModel.insertArticle(postData).then(async res => {
      handleSuccess(ctx, { status: 201, message: ArticleCode.SUCCESS_CREATE_ARTICLE, code: 10001, data: null })
    }).catch(err => {
      handleFail({ message: ServerCode.ERROR_CREATE_ARTICLE, code: 500, data: null })
    })
  }
  static async delete(ctx) {
    const postData = ctx.params
    console.log(postData)
    await ArticleModel.deleteArticle(postData).then(async res => {
      console.log(res)
      if (res.affectedRows > 0) {
        handleSuccess(ctx, { status: 200, message: ArticleCode.SUCCESS_DELETE_ARTICLE, code: 10001, data: null })
      } else {
        handleFail(ctx, { status: 404, message: ArticleCode.FAIL_DELETE_ARTICLE, code: 10001, data: null })
      }
    }).catch(err => {
      handleFail({ message: ServerCode.ERROR_DELETE_ARTICLE, code: 500, data: null })
    })
  }
  static async update(ctx) {
    console.log('sdjaf')
  }
  static async read(ctx) {
    // 【请问在控制器里面如何获取 tid】
    const postData = ctx.params

    await ArticleModel.getArticle(postData).then(async res => {
      if (res.length > 0) {
        handleSuccess(ctx, { status: 200, message: ArticleCode.SUCCESS_GET_ARTICLE, code: 10001, data: res[0] })
      } else {
        handleFail(ctx, { status: 404, message: ArticleCode.FAIL_GET_ARTICLE, code: 10001, data: null })
      }
    }).catch(err => {
      handleFail({ message: ServerCode.ERROR_GET_ARTICLE, code: 500, data: null })
    })
  }
  static async hots(ctx) {
    await ArticleModel.getHotArticles().then(async res => {
      if (res.length > 0) {
        handleSuccess(ctx, { status: 200, message: ArticleCode.SUCCESS_GET_ARTICLE, code: 10001, data: res })
      } else {
        handleFail(ctx, { status: 404, message: ArticleCode.FAIL_GET_ARTICLE, code: 10001, data: null })
      }
    }).catch(err => {
      handleFail({ message: ServerCode.ERROR_GET_ARTICLE, code: 500, data: null })
    })
  }
}

module.exports = Article